import tim from '../../tim';
import TIM from 'tim-js-sdk';

const conversation = {
  state: {
    currentConversation:{},
    conversationList: [],
    currentMessageList: [],
    nextReqMessageID: '',
    isCompleted: false, // 当前会话消息列表是否已经拉完了所有消息
    isAddConversationItemVisible: false
  }, 
  getters: {
    toAccount: state => {
      if (!state.currentConversation || !state.currentConversation.conversationID) {
        return '';
      }
      switch (state.currentConversation.type) {
        case 'C2C':
          return state.currentConversation.conversationID.replace('C2C', '');
        case 'GROUP':
          return state.currentConversation.conversationID.replace('GROUP', '');
        default:
          return state.currentConversation.conversationID;
      }
    }
  },
  mutations: {
    toggleIsAddConversationItemVisible(state, isAddConversationItemVisible){
      state.isAddConversationItemVisible = typeof isAddConversationItemVisible === 'undefined' ? !state.isAddConversationItemVisible : isAddConversationItemVisible;
    },
    updateCurrentConversation(state, conversation) {
      state.currentConversation = conversation;
      state.currentMessageList = [];
      state.nextReqMessageID = '';
      state.isCompleted = false;
    },
    updateConversationList(state, conversationList) {
      state.conversationList = conversationList;
    },
    resetCurrentConversation(state) {
      // 重置当前会话
      state.currentConversation = {},
      state.currentMessageList = []
    },
    pushCurrentMessageList(state, data) {
      // 还没当前会话，则跳过
      if (!state.currentConversation.conversationID) {
        return;
      }
      if (Array.isArray(data)) {
        // 筛选出当前会话的消息
        const result = data.filter(item => item.conversationID === state.currentConversation.conversationID);
        state.currentMessageList = [...state.currentMessageList, ...result];
      } else if (data.conversationID === state.currentConversation.conversationID) {
        state.currentMessageList = [...state.currentMessageList, data];
      }
    },
    removeMessage(state, message) {
      const index = state.currentMessageList.findIndex(({ ID }) => ID === message.ID);
      if (index >= 0) {
        state.currentMessageList.splice(index, 1);
      }
    },
    reset(state){
      Object.assign(state, {
        currentConversation:{},
        conversationList: [],
        currentMessageList: [],
        nextReqMessageID: '',
        isCompleted: false,
        isAddConversationItemVisible: false
      });
    }
  },
  actions: {
    /**
     * 获取消息列表
     * 调用时机：打开某一会话时或下拉获取历史消息时
     * 该接口会优先拉取缓存，即只有第一次会从云端拉取消息
     */
    getMessageList(context, conversationID) {
      if (context.state.isCompleted) {
        context.commit('showMessage', { message: '已经没有更多的历史消息了哦', type: 'info' });
        return
      }
      const { nextReqMessageID, currentMessageList } = context.state;
      tim.getMessageList({ conversationID, nextReqMessageID, count: 15 }).then(imReponse => {
        // 更新messageID，续拉时要用到
        context.state.nextReqMessageID = imReponse.data.nextReqMessageID;
        context.state.isCompleted = imReponse.data.isCompleted;
        // 更新当前消息列表，从头部插入
        context.state.currentMessageList = [...imReponse.data.messageList, ...currentMessageList];
      })
    },
    /**
    * 切换会话
    * 调用时机：切换会话时
    */
    checkoutConversation(context, conversationID) {
      // 若点击当前会话时，进行已读上报
      if(context.state.currentConversation.conversationID === conversationID){
        tim.setMessageRead({ conversationID });
        return Promise.resolve();
      }
      context.commit('resetCurrentMemberList');
      // 1.切换会话前，将切换前的会话进行已读上报
      if (context.state.currentConversation.conversationID) {
        context.dispatch('setMessageRead', context.state.currentConversation.conversationID);
      }
      // 2.待切换的会话也进行已读上报
      context.dispatch('setMessageRead', conversationID);
      // 3. 获取会话信息
      tim.getConversationProfile(conversationID).then(({ data }) => {
      // 3.1 更新当前会话
        context.commit('updateCurrentConversation', data.conversation);
        // 3.2 获取消息列表
        context.dispatch('getMessageList', conversationID);
        // 3.3 拉取第一页群成员列表
        if (data.conversation.type === TIM.TYPES.CONV_GROUP) {
          context.commit('updateCurrentGroupProfile', data.conversation.groupProfile);
          context.dispatch('getGroupMemberList', data.conversation.groupProfile.groupID);
        }
        return Promise.resolve();
      });
    },
    sendMessage(context, message){
      tim.sendMessage(message).then(() => {
        context.commit('pushCurrentMessageList', message);
      }).catch(imError => {
        context.commit('showMessage', { message: imError , type: 'error' });
      });
    },
    setMessageRead(context,conversationID){
      tim.setMessageRead({ conversationID }).catch(imError => {
        context.commit('showMessage', { message: imError , type: 'error' });
      });
    }
  }
}

export default conversation;